package com.zsrd.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zsrd.core.response.ResponseSupport;
import com.zsrd.system.aspect.SystemControllerLog;
import com.zsrd.system.aspect.enums.BusinessType;
import com.zsrd.system.aspect.enums.FunctionType;
import com.zsrd.system.domain.*;
import com.zsrd.system.service.SysMenuService;
import com.zsrd.system.service.SysRoleMenuService;
import com.zsrd.system.service.SysRoleService;
import com.zsrd.system.service.SysUserRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/roleManage")
public class RoleController {


    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    // 角色绑定的菜单 查看
    @PostMapping("menu")
    @ApiOperation(value = "角色绑定的菜单", notes = "角色绑定的菜单")
    public ResponseSupport list(@RequestBody SysRoleMenu roleMenu) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleMenu.getRoleId());
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.getBaseMapper().selectList(wrapper);
        if (CollectionUtil.isNotEmpty(sysRoleMenus)) {
            List<String> collect = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            List<SysMenu> sysMenus = sysMenuService.listByIds(collect);
            if (CollectionUtil.isNotEmpty(sysMenus)) {
                // 树形结构转换
                TreeNodeConfig config = new TreeNodeConfig();
                config.setIdKey("menuId");//默认为id可以不设置
                config.setParentIdKey("parentMenuId");//默认为parentId可以不设置
                //config.setDeep(4);//最大递归深度
                //config.setWeightKey("priority");//排序字段

                List<Tree<Long>> build = TreeUtil.build(sysMenus, 0L, config, (object, tree) -> {
                    tree.setId(object.getMenuId());
                    tree.setParentId(object.getParentMenuId());
                    tree.setName(object.getName());
                    tree.putExtra("icon", object.getIcon());
                    tree.putExtra("menuName", object.getMenuName());
                    tree.putExtra("url", object.getPath());
                });
                return ResponseSupport.success(build);
            }
            return ResponseSupport.fail("未查询到当前角色相关权限");
        } else {
            return ResponseSupport.fail("未查询到当前角色相关权限");
        }
    }


    //    角色绑定菜单，修改操作是。每次只给你全量选中的菜单  新增修改
    @SystemControllerLog(title = "修改角色对应的菜单", businessType = BusinessType.UPDATE, funcType = FunctionType.MENUMANAGE)
    @PostMapping("updateMenu")
    @ApiOperation(value = "修改角色对应的菜单", notes = "修改角色对应的菜单")
    public ResponseSupport updateMenu(@RequestBody SysRole sysRole) {
//        int i = 1 / 0;
        Boolean is = sysRoleService.updateMenu(sysRole);
        if (is) {
            return ResponseSupport.success("成功");
        } else {
            return ResponseSupport.fail("所传参数有误");
        }
    }


    /**
     * 删除菜单
     *
     * @return 0代表存在 2 删除
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除", notes = "删除")
    public ResponseSupport delete(@RequestBody SysRole sysRole) {
        sysRole.setDelFlag("2");
        sysRole.setUpdateTime(new Date());
        boolean b = sysRoleService.updateById(sysRole);
        if (b == false) {
            return ResponseSupport.fail("删除失败");
        }
        return ResponseSupport.success(b);
    }


    /**
     * 分页
     *
     * @param
     * @return
     */
    @RequestMapping(value = "query", method = RequestMethod.POST)
    @ApiOperation(value = "分页角色条件查询", notes = "分页角色条件查询")
    public ResponseSupport query(@RequestBody SysRole sysRole) {
        IPage<SysRole> sysRoles = sysRoleService.listByPage(sysRole);
        return ResponseSupport.success(sysRoles);
    }


    /**
     * 编辑回显接口
     */
    @PostMapping("display")
    @ApiOperation(value = "编辑回显接口", notes = "编辑回显接口")
    public ResponseSupport display() {

        List<SysMenu> sysMenus = sysMenuService.list();
        if (CollectionUtil.isNotEmpty(sysMenus)) {
            // 树形结构转换
            TreeNodeConfig config = new TreeNodeConfig();
            config.setIdKey("menuId");//默认为id可以不设置
            config.setParentIdKey("parentMenuId");//默认为parentId可以不设置
            //config.setDeep(4);//最大递归深度
            //config.setWeightKey("priority");//排序字段

            List<Tree<Long>> build = TreeUtil.build(sysMenus, 0L, config, (object, tree) -> {
                tree.setId(object.getMenuId());
                tree.setParentId(object.getParentMenuId());
                tree.putExtra("menuName", object.getMenuName());
            });
            return ResponseSupport.success(build);
        }
        return ResponseSupport.fail("查询失败");
    }

    /**
     * 查询角色对应的用户
     * @return
     */
    @PostMapping("/userRole")
    public ResponseSupport UserRole(@RequestBody SysRole sysRole) {
        IPage<SysUser> users = sysRoleService.listByRole(sysRole);
        return ResponseSupport.success(users);
    }



    /**
     * 传角色和用户的id
     *
     * 解除关联用户
     */
    @PostMapping("/disRoleUsers")
    public ResponseSupport disRoleUsers(@RequestBody SysUserRole sysUserRole) {
        // 删除中间表
        sysUserRoleService.deleteRole(sysUserRole);
        return ResponseSupport.success("删除成功");
    }

}
